// src/models/specType.model.js
import { DataTypes } from "sequelize";

export default function initSpecType(sequelize) {
  const SpecType = sequelize.define(
    "SpecType",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: DataTypes.STRING(50),
        allowNull: false,
        comment: "规格类型名称（如颜色、尺寸）",
      },
      category_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        comment: "关联的商品分类ID",
      },
      // 添加 values 字段,冗余字段检查
      values: {
        type: DataTypes.JSON,
        allowNull: false,
        defaultValue: [], // 设置默认值
        get() {
          const rawValue = this.getDataValue("values");
          return rawValue ? rawValue : [];
        },
        comment: '规格可选值（如["红","蓝"]）',
      },
      deleted_at: {
        type: DataTypes.DATE,
        allowNull: true,
        comment: "删除时间",
      },

      description: {
        type: DataTypes.STRING(255),
        allowNull: true,
        comment: "规格类型描述",
      },
    },
    {
      tableName: "spec_type",
      paranoid: true, // 启用软删除
    }
  );

  // 关联关系配置
  SpecType.associate = function (models) {
    SpecType.belongsToMany(models.Product, {
      through: {
        model: models.SkuSpec,
        unique: false,
      },
      foreignKey: "spec_type_id",
      otherKey: "sku_id",
      as: "products",
    });
    // 定义与SkuSpec的一对多关系
    SpecType.hasMany(models.SkuSpec, {
      foreignKey: "spec_type_id",
      as: "skuSpecs",
    });
    // 定义与SpecValue的一对多关系
    SpecType.hasMany(models.SpecValue, {
      foreignKey: "spec_type_id",
      as: "specValues", // 这个别名必须与查询时使用的别名一致
    });
  };

  return SpecType;
}
